package com.bodacn.storagescan;

import androidx.appcompat.app.AppCompatActivity;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.InputType;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpResponseException;
import org.ksoap2.transport.HttpTransportSE;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.URL;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    private final static String TAG = LoginActivity.class.getSimpleName();
    private final static int MSG_ChangePSWOver = 9001;
    private final static int MSG_LoginCheckOver = 9002;
    private final static int MSG_AllowScan = 9003;
    private Button btn_LoginSYS;
    private ImageButton btn_guide_setup, btn_ViewPass, btn_ExitSYS;
    private EditText edit_LoginUserNo, edit_LoginPassword;
    private TextView txt_SoftVer;
    private CheckBox check_SavePsw;
    /* 保存解析的XML信息 */
    HashMap<String, String> ServerConfig;
    FrameLayout frame_main;
    public static boolean NeedUpdate = false;
    //全局提示;
    Toast curToast;
    private ProgressDialog waitDialog = null;
    //全局变量
    String STORE_NAME = "Settings";
    String serviceUrl = "http://192.168.1.1/BDCOMM";
    String agvUrl = "http://192.168.1.1/BDCOMM";
    String serviceUrlExt = "/BDService.asmx?wsdl";
    MainApplication mApp;
    String curLoginUserNo, curLoginUser, curLoginTime, curUserPower = "";//操作员所属部门等信息;
    String SQLAddr = "", SQLUser = "", SQLPsw = "", SQLDBName = "";
    private JSONArray loginJSONArray;//用于接收登陆返回信息;
    boolean isHideChar = false;
    boolean ScanSign = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        InitView();
        try {
            String SoftVer = getVersionName();
            txt_SoftVer.setText("VER:" + SoftVer);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("Build.VERSION.SDK_INT:" + Build.VERSION.SDK_INT);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //获取窗口区域
            Window window = this.getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            //设置显示为白色背景，黑色字体
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }

        mApp = (MainApplication) getApplication();
    }


    //获取软件版本;
    private String getVersionName() throws Exception {
        // 获取packagemanager的实例
        PackageManager packageManager = getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(), 0);
        String version = packInfo.versionName;
        return version;
    }

    //初始化;
    private void InitView() {
        frame_main = findViewById(R.id.frame_main);
        frame_main.setOnClickListener(this);
        btn_LoginSYS = findViewById(R.id.btn_LoginSYS);
        btn_LoginSYS.setOnClickListener(this);
        btn_ExitSYS = findViewById(R.id.btn_ExitSYS);
        btn_ExitSYS.setOnClickListener(this);
        check_SavePsw = findViewById(R.id.check_SavePsw);
        btn_ViewPass = findViewById(R.id.btn_ViewPass);
        btn_ViewPass.setOnClickListener(this);
        btn_guide_setup = findViewById(R.id.btn_guide_setup);
        btn_guide_setup.setOnClickListener(this);
        edit_LoginUserNo = findViewById(R.id.edit_LoginUserNo);
        edit_LoginUserNo.setInputType(InputType.TYPE_NULL);
        edit_LoginUserNo.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event != null) {
                    if ((keyCode == KeyEvent.KEYCODE_ENTER) && (edit_LoginUserNo.getText().toString().length() > 0)) {
                        edit_LoginPassword.setFocusable(true);
                        edit_LoginPassword.requestFocus();
                        edit_LoginPassword.requestFocusFromTouch();
                    }
                }
                return false;
            }
        });
        edit_LoginUserNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edit_LoginUserNo.selectAll();
                edit_LoginUserNo.setFocusable(true);
                edit_LoginUserNo.setInputType(InputType.TYPE_CLASS_TEXT);
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) getSystemService(LoginActivity.this.INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(edit_LoginPassword, InputMethodManager.SHOW_FORCED);
            }
        });
        edit_LoginUserNo.setFocusableInTouchMode(true);
        edit_LoginUserNo.setFocusable(true);
        edit_LoginUserNo.requestFocus();
        edit_LoginUserNo.requestFocusFromTouch();
        //显示控制;
        edit_LoginPassword = findViewById(R.id.edit_LoginPassword);
        edit_LoginPassword.setInputType(InputType.TYPE_NULL);
        edit_LoginPassword.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event != null) {
                    if ((event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                        edit_LoginPassword.setInputType(InputType.TYPE_NULL);
                        //1.得到InputMethodManager对象
                        InputMethodManager imm = (InputMethodManager) getSystemService(LoginActivity.this.INPUT_METHOD_SERVICE);
                        //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                        IBinder windowToken = edit_LoginPassword.getWindowToken();
                        if (windowToken != null) {
                            imm.hideSoftInputFromWindow(windowToken, 0);
                        }
                        loginCheck();
                    }
                }
                return false;
            }
        });
        edit_LoginPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edit_LoginPassword.setFocusable(true);
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) getSystemService(LoginActivity.this.INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(edit_LoginPassword, InputMethodManager.SHOW_FORCED);
            }
        });
        edit_LoginPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        edit_LoginPassword.setFocusableInTouchMode(true);
        edit_LoginPassword.setFocusable(true);
        txt_SoftVer = findViewById(R.id.txt_SoftVer);
        frame_main = findViewById(R.id.frame_main);
        //初始提醒;
        curToast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_LONG);
        //curToast.setGravity(Gravity.CENTER, 0, 0);
        //提示框pd=new ProgressDialog(this);
        waitDialog = new ProgressDialog(this);
        waitDialog.setTitle(getString(R.string.SystemHint));
    }

    //通过消息来执行处理类程序,不更新UI则不一定需要通过这个;
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // TODO Auto-generated method stub
            // 根据消息ID来判断要做的事情
            int msgId = msg.what;
            switch (msgId) {
                case MSG_ChangePSWOver:
                    Log.d("msg", "ChangePSW--------------------1");
                    try {
                        if (loginJSONArray != null) {
                            Log.d("msg", "ChangePSW--------------------1");
                            if (loginJSONArray.optJSONObject(0).get("ChangePSW").equals("OK")) {
                                if (loginJSONArray.optJSONObject(0).has("LoginUserNo"))
                                    curLoginUserNo = loginJSONArray.optJSONObject(0).get("LoginUserNo").toString();
                                if (loginJSONArray.optJSONObject(0).has("LoginUser"))
                                    curLoginUser = loginJSONArray.optJSONObject(0).get("LoginUser").toString();
                                if (loginJSONArray.optJSONObject(0).has("LoginTime"))
                                    curLoginTime = loginJSONArray.optJSONObject(0).get("LoginTime").toString();
                                curToast.setText(getString(R.string.ChangPswOKInfo));
                                curToast.show();
                            } else {
                                curToast.setText(getString(R.string.ChangPswErrInfo));
                                curToast.show();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case MSG_LoginCheckOver:
                case MSG_AllowScan:
                    try {
                        if (loginJSONArray != null) {
                            if (loginJSONArray.optJSONObject(0).getString("LoginCheck").equals("OK")) {
                                if (loginJSONArray.optJSONObject(0).has("LoginUser"))
                                    curLoginUser = loginJSONArray.optJSONObject(0).get("LoginUser").toString();
                                if (loginJSONArray.optJSONObject(0).has("LoginUserNo"))
                                    curLoginUserNo = loginJSONArray.optJSONObject(0).get("LoginUserNo").toString();
                                if (loginJSONArray.optJSONObject(0).has("LoginTime"))
                                    curLoginTime = loginJSONArray.optJSONObject(0).get("LoginTime").toString();
                                if (loginJSONArray.optJSONObject(0).has("UserPower"))
                                    curUserPower = loginJSONArray.optJSONObject(0).getString("UserPower");
                                //登陆界面;
                                loginOK();
                            } else {
                                curToast.setText(getString(R.string.PleaseCheckEmpNoPSW));
                                curToast.show();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    break;
            }
        }
    };

    //md5加密
    private String MD5(String s) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = md.digest(s.getBytes("utf-8"));
            return toHex(bytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static String toHex(byte[] bytes) {

        final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
        StringBuilder ret = new StringBuilder(bytes.length * 2);
        for (int i = 0; i < bytes.length; i++) {
            ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);
            ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
        }
        return ret.toString();
    }

    @Override
    protected void onResume() {
        super.onResume();
        hideIM(edit_LoginUserNo);
        //读取配置文件;
        Log.e(TAG, "-----------------------------------------onResume-----------------------------------------");
        getPref();
        Log.e(TAG, "serviceUrl" + serviceUrl);
        GetServerConfig(serviceUrl + "/SysConfig.xml");
        //下载最新的版本文件,检查是否需要升级;
        AutoUpdate autoupdate = new AutoUpdate(this, "com.bodacn.storagescan");
        autoupdate.CheckWebUpdate(serviceUrl + "/UPDATE/storagescan.xml");
        System.out.println(TAG + "OnResume");
    }


    //从网络获取版本升级文件
    public void GetServerConfig(String serviceUrl) {
        //组织参数传到匿名类中;
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("serviceUrl", serviceUrl);
        //创建匿名类用于WebService调用;
        new AsyncTask<Map<String, Object>, Void, String>() {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected String doInBackground(Map<String, Object>... params) {
                boolean ErrSign = false;
                String serviceUrl = (String) params[0].get("serviceUrl");
                Log.d("GetServerConfig", "文件接收A:---" + serviceUrl);
                try {
                    ParseXmlService service = new ParseXmlService();
                    InputStream inStream = new URL(serviceUrl).openStream();
                    System.out.println("服务器配置文件获取成功....");
                    ServerConfig = service.parseXml(inStream);
                    System.out.println(ServerConfig);
                    System.out.println("服务器配置文件解析成功....");
                    return "OK";
                } catch (HttpResponseException e) {
                    ErrSign = true;
                    e.printStackTrace();
                } catch (SoapFault soapFault) {
                    ErrSign = true;
                    soapFault.printStackTrace();
                } catch (IOException e) {
                    ErrSign = true;
                    e.printStackTrace();
                } catch (Exception e) {
                    ErrSign = true;
                    e.printStackTrace();
                }
                //关闭ProgressDialog
                if (ErrSign == true) Log.d(TAG, "获取服务器配置文件异常,错误异常抛出！");
                return "NO";
            }

            @Override
            protected void onPostExecute(String rtnstr) {
                super.onPostExecute(rtnstr);
                if ((rtnstr == null) || (rtnstr == "NO")) {
                    curToast.setText("服务器配置更新文件下载错误");
                    curToast.show();
                    return;
                } else {
                    curToast.setText("服务器配置文件获取成功");
                    curToast.show();
                }
                //判断版本是否相同;
                if (null != ServerConfig) {
                    SQLAddr = ServerConfig.get("ServerIP");
                    SQLUser = ServerConfig.get("UserName");
                    SQLPsw = ServerConfig.get("Password");
                    SQLDBName = ServerConfig.get("DBName");
                    DBUtil.ServerIP = SQLAddr;
                    DBUtil.UserName = SQLUser;
                    DBUtil.Password = SQLPsw;
                    DBUtil.DBName = SQLDBName;
                    Log.i(TAG, "SQLAddr:" + SQLAddr + " SQLUser:" + SQLUser + " SQLPsw:" + SQLPsw + " SQLDBName:" + SQLDBName);
                    setPref();
                }

            }
        }.execute(params);

    }

    //获取配置;
    private void getPref() {
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
        serviceUrl = settings.getString("serviceUrl", serviceUrl);
        agvUrl = settings.getString("agvUrl", agvUrl);
        curLoginUserNo = settings.getString("LoginUserNo", curLoginUserNo);
        edit_LoginUserNo.setText(curLoginUserNo);
        check_SavePsw.setChecked(settings.getInt("SavePassword", 0) == 1);
        if (check_SavePsw.isChecked()) {
            edit_LoginPassword.setText(settings.getString("LoginPassword", edit_LoginPassword.getText().toString()));
        }
        SQLAddr = settings.getString("SQLAddr", SQLAddr);
        SQLUser = settings.getString("SQLUser", SQLUser);
        SQLPsw = settings.getString("SQLPsw", SQLPsw);
        SQLDBName = settings.getString("SQLDBName", SQLDBName);
        //数据连接类赋值;
        DBUtil.ServerIP = SQLAddr;
        DBUtil.UserName = SQLUser;
        DBUtil.Password = SQLPsw;
        DBUtil.DBName = SQLDBName;
    }


    //获取配置;
    private void setPref() {
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
        editor.putString("SQLAddr", SQLAddr);
        editor.putString("SQLUser", SQLUser);
        editor.putString("SQLPsw", SQLPsw);
        editor.putString("SQLDBName", SQLDBName);
        editor.apply();
    }

    private void showTips() {
        AlertDialog alertDialog = new AlertDialog.Builder(this)
                .setTitle(getString(R.string.SystemHint)).setMessage(getString(R.string.SystemExitConfirm))
                .setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Intent exit = new Intent(Intent.ACTION_MAIN);
                        exit.addCategory(Intent.CATEGORY_HOME);
                        exit.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(exit);
                        System.exit(0);
                        //finish();
                    }

                }).setNegativeButton(getString(R.string.Cancel),

                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                return;
                            }
                        }).create(); // 创建对话框
        alertDialog.show(); // 显示对话框
    }

    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //当处理初始Fragment，则返回;
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            showTips();
        }
        return super.onKeyDown(keyCode, event);
    }

    //登陆成功
    private void loginOK() {
        System.out.println(TAG + ":Login OK");
        //隐藏键盘
        hideIM(edit_LoginPassword);
        new Thread() {
            public void run() {
                try {
                    sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
        waitDialog.cancel();
        //跳转前关闭键盘
        Intent mainActivity = new Intent(LoginActivity.this, MainActivity.class);
        //简单参数通过Intent的Extras传递;
        Bundle paramBundle = new Bundle();
        paramBundle.putString("LoginUserNo", curLoginUserNo);
        paramBundle.putString("LoginUser", curLoginUser);
        paramBundle.putString("LoginTime", curLoginTime);
        paramBundle.putString("serviceUrl", serviceUrl);
        paramBundle.putString("agvUrl", agvUrl);
        paramBundle.putString("serviceUrlExt", serviceUrlExt);
        paramBundle.putString("UserPower", curUserPower);
        mainActivity.putExtras(paramBundle);
        //启动主界面;
        startActivity(mainActivity);

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    //登陆校验;
    private void loginCheck() {
        String tmpPassword = edit_LoginPassword.getText().toString();
        //登陆判断
        if (tmpPassword.length() > 0) {
            // 在这里使用的是encode方式，返回的是byte类型加密数据，可使用new String转为String类型
            tmpPassword = new String(Base64.encode(tmpPassword.getBytes(), Base64.DEFAULT));
            Log.i("Test", "tmpPassword>>>" + tmpPassword);
        }
        edit_LoginUserNo.setInputType(InputType.TYPE_NULL);
        edit_LoginPassword.setInputType(InputType.TYPE_NULL);
        //保存配置文件
        saveSetup();
        //组织WebService地址;
        String sqlComm = "Exec App_LoginCheck @UserNo='" + edit_LoginUserNo.getText().toString() + "',@PassWord='" + tmpPassword.replaceAll("\r|\n", "") + "'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(sqlComm);
        edit_LoginPassword.setText("");

    }


    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        ScanSign = true;
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    JSONArray jsonArray = DBUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    ScanSign = false;
                    //往界面转数据;
                    if ((jsonArray != null) && (jsonArray.length() > 0)) {
                        //返回的登陆信息;
                        if (jsonArray.optJSONObject(0).has("LoginCheck") == true) {
                            loginJSONArray = jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_LoginCheckOver;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                        //返回的登陆信息;
                        if (jsonArray.optJSONObject(0).has("ChangePSW") == true) {
                            loginJSONArray = jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_ChangePSWOver;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                            Log.d("msg", "ChangePSW--------------------1");
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    //刷新界面;
                    ScanSign = false;
                    Message msg = new Message();
                    msg.what = MSG_AllowScan;
                    handler.removeMessages(msg.what);
                    handler.sendMessage(msg);
                }

            }

        };
        new Thread(run).start();

    }


    @Override
    public void onClick(View view) {
        hideIM(view);
        switch (view.getId()) {
            case R.id.btn_LoginSYS:
                if ((edit_LoginUserNo.getText() != null) && (edit_LoginPassword.getText() != null)) {
                    if (edit_LoginUserNo.getText().length() == 0) {
                        curToast.setText(getString(R.string.PleaseInputEmpNo));
                        curToast.show();
                    } else {
                        loginCheck();
                    }
                } else {
                    curToast.setText("请输入用户名及密码!");
                    curToast.show();
                }
                break;
            case R.id.btn_ExitSYS:
                showTips();
                break;
            case R.id.btn_guide_setup:
                showSetup();
                break;
            case R.id.btn_ViewPass:
                Log.d(TAG, "onCheckedChanged: " + isHideChar);
                isHideChar = !isHideChar;
                if (isHideChar) {
                    //选择状态 显示明文--设置为可见的密码
                    edit_LoginPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    //默认状态显示密码--设置文本 要一起写才能起作用 InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD
                    edit_LoginPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                break;
            default:
                break;
        }
    }

    //修改密码
    private void changepsw() {
        //创建布局
        LayoutInflater inflater = this.getLayoutInflater();
        final View guide_setup = inflater.inflate(R.layout.guide_changepsw, null);
        //Activity.findViewById最终还是会调用View.findViewById
        //因为在Activity的onCreate中一定会先setContentView的
        final EditText text_password_old = guide_setup.findViewById(R.id.text_password_old);
        final EditText text_password_new = guide_setup.findViewById(R.id.text_password_new);
        final EditText text_password_new2 = guide_setup.findViewById(R.id.text_password_new2);
        //创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(guide_setup).setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Field field = null;
                        hideIM(guide_setup);
                        String tmpOldPassword = text_password_old.getText().toString();
                        String tmpNewPassword = text_password_new.getText().toString();
                        String tmpNewPassword2 = text_password_new2.getText().toString();
                        Log.i("Test", "tmpOldPassword>>>" + tmpOldPassword + "----tmpNewPassword>>>" + tmpNewPassword + "----tmpNewPassword2>>>" + tmpNewPassword2);
                        if ((tmpNewPassword.length() > 0) && (tmpNewPassword.equals(tmpNewPassword2))) {
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                                field.setAccessible(true);
                                field.set(dialog, true);
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                            //调用登陆过程;
                            String SqlComm = "Exec App_ChangePSW @UserNo='" + edit_LoginUserNo.getText().toString() + "',@OldPassWord='" + tmpOldPassword.replaceAll("\r|\n", "") + "',@NewPassWord='" + tmpNewPassword.replaceAll("\r|\n", "") + "'";
                            //调用WebService过程并处理界面更新;
                            ReadSQLData(SqlComm);
                        } else {
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                                field.setAccessible(true);
                                field.set(dialog, false);
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                            curToast.setText(getString(R.string.PasswordConfirmErr));
                            curToast.show();
                        }
                    }
                }
        ).setNegativeButton(getString(R.string.Cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    hideIM(guide_setup);
                    Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
                    field.setAccessible(true);
                    field.set(dialog, true); // true - 使之可以关闭(此为机关所在，其它语句相同)
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
                Log.v("tag", getString(R.string.Cancel));
            }
        }).setTitle(getString(R.string.SoftTitle));
        builder.show();
    }

    private void showSetup() {
        //创建布局
        LayoutInflater inflater = this.getLayoutInflater();
        final View guide_setup = inflater.inflate(R.layout.guide_setup, null);
        //Activity.findViewById最终还是会调用View.findViewById
        //因为在Activity的onCreate中一定会先setContentView的
        final EditText text_serverUrl = guide_setup.findViewById(R.id.text_serverUrl);
        text_serverUrl.setText(serviceUrl);
        final EditText text_agvUrl = guide_setup.findViewById(R.id.text_agvUrl);
        text_agvUrl.setText(agvUrl);
        //创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(guide_setup).setPositiveButton(getString(R.string.Affirm), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Log.v("tag", text_serverUrl.getText().toString());
                        serviceUrl = text_serverUrl.getText().toString();
                        agvUrl = text_agvUrl.getText().toString();
                        saveSetup();

                        hideIM(guide_setup);

                        GetServerConfig(serviceUrl + "/SysConfig.xml");
                        //下载最新的版本文件,检查是否需要升级;
                        AutoUpdate autoupdate = new AutoUpdate(LoginActivity.this, "com.bodacn.storagescan");
                        autoupdate.CheckWebUpdate(serviceUrl + "/UPDATE/storagescan.xml");
                    }
                }
        ).setNegativeButton(getString(R.string.Cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                hideIM(guide_setup);
                Log.v("tag", getString(R.string.Cancel));
            }
        }).setTitle(getString(R.string.SetupInfo));
        builder.show();
    }


    private void saveSetup() {
        //登陆成功后保存配置;
        SharedPreferences.Editor set_editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
        set_editor.putString("LoginUserNo", edit_LoginUserNo.getText().toString());
        set_editor.putString("serviceUrl", serviceUrl);
        set_editor.putString("agvUrl", agvUrl);
        if (check_SavePsw.isChecked()) {
            set_editor.putInt("SavePassword", 1);
            set_editor.putString("LoginPassword", edit_LoginPassword.getText().toString());
        } else {
            set_editor.putString("LoginPassword", "");
            set_editor.putInt("SavePassword", 0);
        }
        set_editor.commit();

        mApp.AgvUrl = agvUrl;
    }
}